package edu.zut.main.thread;

public class BankDrawMoney {
    public static void main(String[] args) {
        Account account = new Account(100);
        Drawing drawing = new Drawing(account, 30);
        Drawing drawing1 = new Drawing(account, 60);
        new Thread(drawing,"小明").start();
        new Thread(drawing1,"花花").start();
    }
}

//银行账户
class Account{

    int money;
    public Account(int money) {
        this.money = money;
    }

}

//模拟银行取钱
class Drawing implements Runnable{

    private Account account; //要操作的账户
    private int drawMoney;   //取款额

    public Drawing(Account account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }

    /**
     * 为了保证取款在一个时间点上，每次只能被一个人操作，我们可以将取款操作（对象）给锁起来，进行安全控制
     * 但是，同步操作它实际上是对对象的同步，同步方法默认同步的就是方法所属的对象
     * 同理，run里面是我们的同步操作，我们也可以将需要同步的操作（对象）进行锁定，保证安全
     * 即为同步代码块，同步代码块可以指定需要同步的对象
     */
    //取款
    public void withDrawMoney(){
        synchronized (account) {
            //判断余额是否充足
            if (account.money - drawMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }
            //出现延时操作
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //余额足够
            account.money -= drawMoney;
            System.out.println(Thread.currentThread().getName() + "取款后余额为：" + account.money);
        }
    }


    //取款
    @Override
    public void run() {
        withDrawMoney();
    }
}



